/**
 * 华农教师信息系统
 */
import parallelLimit from 'async/parallelLimit';
import eachLimit from 'async/eachLimit';
import { UTF8Request } from '../utils/request';
import { insertData } from '../db/index';
import CONFIG from '../config/config';

const cheerio = require('cheerio');

const URL = 'http://pdc.hzau.edu.cn/jgfw/desktop/grzy/initQuery.htm';

const typesArr = [
  '教授',
  '副教授',
  '其他专业技术',
];

let goingCount = 0;

function getOptions(type = '其他专业技术') {
  return {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    formData: {
      jszw: type,
      start: 0,
      limit: 10000, // 一次直接全部获取到
      deptId: '',
      teacherName: '',
    },
  };
}

// 获取链接最后的一串id数字
function getPageID(type, callback) {
  UTF8Request(URL, 'POST', getOptions(type))
    .then((data) => {
      let teacherPageInfoArr = [];
      if (data) {
        teacherPageInfoArr = JSON.parse(data).personPage.rows.map(v => v.zgh);
      } else {
        console.trace('教师列表信息获取失败 => no data');
      }
      if (typeof callback === 'function') {
        callback(null, teacherPageInfoArr);
      }
    })
    .catch((err) => {
      if (typeof callback === 'function') {
        callback(null, []);
      }
      console.trace('教师列表信息获取失败 => ', err);
    });
}

// 获取具体链接
function getPageLink(cb) {
  parallelLimit(typesArr.map(v => callback => getPageID(v, callback)), 1, (err, result) => {
    if (err) {
      cb([]);
      console.trace('并行执行任务出错', err);
    } else {
      // http://pdc.hzau.edu.cn/jgfw/desktop/grzy/show.htm?zgh=
      let resultArr = [];
      result.forEach((v) => {
        resultArr = resultArr.concat(v);
      });
      const links = resultArr.map(v => `http://pdc.hzau.edu.cn/jgfw/desktop/grzy/show.htm?zgh=${v}`);
      console.log('获取教师链接列表完毕');
      cb(links);
    }
  });
}

function getTeacherDetail(url, callback) {
  goingCount += 1;
  UTF8Request(url)
  .then((data) => {
    const info = {
      link: url,
      intro: '',
    };
    if (data) {
      const $ = cheerio.load(data);
      $('body').children('div').eq(0)
        .children('.personw2')
        .children('.zj')
        .children('div')
        .each(function (i) {
          if (i === 0) {
            info.avatar = `http://pdc.hzau.edu.cn${$(this).children('img').attr('src')}`;
          } else {
            info.name = $(this).find('.user-name').text().trim();
            info.sex = '无';
            $(this).find('.user-in').children('li').each(function (ii) {
              if (ii === 0) {
                info.title = $(this).children('strong').text().trim() || '无';
              } else if (ii === 1) {
                info.college = $(this).find('strong').text().trim() || '无';
              } else if (ii === 2) {
                info.phone = $(this).find('strong').text().trim() || '无';
              } else if (ii === 3) {
                info.email = $(this).find('strong').text().trim() || '无';
              }
            });
          }
        });
      info.qualification = '无';
      // intro
      info.intro = `<b>个人简介</b> <br />${$('#grjjContext').text().trim()}<br /><b>代表性论文</b> <br />`;
      $('#kylwContext .kylwContextul').children('li').each(function () {
        info.intro += `${$(this).text().trim()}<br />`;
      });
      $('#kyxmContext .kylwContextul').children('li').each(function () {
        info.intro += `${$(this).text().trim()}<br />`;
      });
      if (CONFIG.showInsertInfo) {
        console.log(info);
      }
      insertData(info);
    } else {
      console.trace('获取教师详细信息失败', url);
    }
  })
  .catch((err) => {
    console.trace('获取教师详细信息失败', err);
  })
  .finally(() => {
    if (CONFIG.showFinishedCount) {
      console.log(`finished ->  ${goingCount}`);
    }
    callback();
  });
}


// 具体页面信息采集
export default function PacSpider(cb) {
  getPageLink((arr) => {
    eachLimit(arr, CONFIG.parallelCount, (url, callback) => {
      getTeacherDetail(url, callback);
    }, (err) => {
      if (err) {
        console.trace('获取具体某教师信息失败', err);
      } else {
        console.log('<<<+++++++++++ 获取信息 over +++++++++++>>>');
      }
      cb(null, arr.length);
    });
  });
}

